<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
use App\Models\User;

class Article extends Model
{
	use HasDateTimeFormatter;
    use SoftDeletes;

    /**
     * 保存
     *
     * @var array
     */
    protected $fillable = [
        'user_id','title','abstract','tags','content','path','view_count','comment_count','status','ip'
    ];

    /**
     * 展示
     *
     * @var array
     */
    protected $visible = [
        'id','user_id','title','abstract','tags','content','path','view_count','comment_count','status','ip', 'updated_at'
    ];

    /**
     * 隐藏
     *
     * @var array
     */
    protected $hidden = [];

    /**
     * 强制类型转换.
     *
     * @var array
     */
    protected $casts = [
        'tags' => 'json',
    ];

    /**
     * 后加属性
     *
     * @var array
     */
    protected $appends = [
        'images'
    ];

    public function author()
    {
        return $this->belongsTo(User::class,'user_id');
    }

    /**
     * 获取MD文档里的图片
     *
     * @param string $md markdown内容
     * @return array 默认图片 or md文档图片
     */
    public static function getMDImage($md){
        //正则表达式为 !\[.*\]\(.+\)!，然后我们把我们想要的内容用 () 括起来即可
        $regular = '!\[(.*)\]\((.+)\)!';
        preg_match_all($regular, $md, $match);
        $images = [['alt' => '默认图片','image'=> '/images/default.jpg']];
        if(count($match[2]) > 0){
            $images = [];
            foreach ($match[2] as $key => $image){
                $images[] = ['alt' => $match[1][$key],'image'=> $image];
            }
        }
        return $images;
    }

    public function setImagesAttribute()
    {
        $cacheKey = "arts_images_{$this->id}";
        \Cache::forever($cacheKey, Article::getMDImage($this->content));

    }

    public function getImagesAttribute()
    {
        $cacheKey = "arts_images_{$this->id}";
        $images = \Cache::get($cacheKey);
        if(is_null($images)){
            $images = Article::getMDImage($this->content);
            \Cache::forever($cacheKey, $images);
        }
        return $images;
    }

}
